<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('form', 'url'));  
  		$this->load->library('form_validation');
  		
  		$this->load->database();
  		$this->load->model('User_Model');
  		
	}
	public function index()
	{
		$this->form_validation->set_rules('username', '账号', 'required|valid_email|callback_Account_Check');
		$this->form_validation->set_rules('password', '密码', 'required|callback_Password_Check');
		$this->form_validation->set_message('required', '%s不能为空');
		$this->form_validation->set_message('valid_email', '%s不是正确的邮箱格式');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('login/login');
		}
		else 
		{
			redirect('/Infopage');
		}
	}
	
	public function Account_Check($str)
	{
		$result=$this->User_Model->query_user($str);
		if(empty($result))
		{
			$this->form_validation->set_message('Account_Check', '不存在此账号');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	public function Password_Check($str)
	{
		$bat=$this->input->post('username');
		$result=$this->User_Model->query_user($bat);
		if(empty($result))
		{
			$this->form_validation->set_message('Password_Check',' ');
			return FALSE;
		}
		else
		{
			if($result[0]['Password']==$str)
			{
				$this->load->library('session');
				$session_array=array('id'=>$result[0]['ID'],
						'account'=>$result[0]['Account'],
						'permission'=>$result[0]['Permission']
				);
				$this->session->set_userdata($session_array);
				return TRUE;
			}
			else 
			{
				$this->form_validation->set_message('Password_Check','密码不正确');
				return FALSE;
			}
		}
	}
// 	public function checkLogin()
// 	{
		
// 		$this->load->database();
// 		$this->load->model('User_Model');
// 		$result=$this->User_Model->query_user($_POST['username']);
//  		$this->load->helper('url');
//  		if(empty($result))
//  		{
//  			redirect('/login');
//  		}
//    		else
//    		{
//    			if($result[0]['Password']==$_POST['password'])
//    			{
//    				$this->load->library('session');
//    				$session_array=array('id'=>$result[0]['ID'],
//    						'account'=>$result[0]['Account']
//    						);
//    				$this->session->set_userdata($session_array);
//    				$this->load->view('info_index');
//    			}
//    			else
//    			{
//    				redirect('/login');
//    			}
//    		}
  		
// 	}
// 	public function checkSession()
// 	{
// 		$this->load->library('session');
// 		$this->load->helper('url');
// 		if($this->session->userdata('id'))
// 		{
// 			redirect('/welcome');
// 		}
// 		else 
// 		{
// 			echo 'session������';
// 		}
// 	}
}

